import math
import os
import random

import gevent
import jieba
from flask import *
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'djaslkfnalksnglanflnflas'
socketio = SocketIO(app)
jieba.set_dictionary('dict/dict.txt')
jieba.initialize()  # 手动初始化（可选）
path = os.getcwd() + "/upload/"
data = ["江苏南京市建邺区友谊街38号9幢一单元103室", "江苏南京市建邺区友谊街38号4幢三单元1411室"]
myumap = {
    '市辖区': '南京市',
    '玄武区': '南京市',
    '鼓楼区': '南京市',
    '秦淮区': '南京市',
    '建邺区': '南京市',
    '浦口区': '南京市',
    '栖霞区': '南京市',
    '雨花台区': '南京市',
    '江宁区': '南京市',
    '六合区': '南京市',
    '溧水区': '南京市',
    '高新开发区': '南京市',
    '经济技术开发区': '南京市',

}


def transform(location_strs, umap=myumap, index=[], cut=True, lookahead=8):
    from word.transformer import CPCATransformer
    # loc这里的作用纯粹是为了让输出结果更好看一些
    word = CPCATransformer(umap)
    # ret = word.transform(location_strs, index, cut, lookahead).loc[:, ('省', '市', '区', '地址')]
    ret = word.transform(location_strs, index, cut, lookahead)
    return ret


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/api/address', methods=['GET'])
def api():
    text = request.args.get('text')
    words = transform([text])
    data = {"code":0,"msg":"ok","data":words}
    return Response(json.dumps(data, ensure_ascii=False), content_type='application/json')


@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = str(random.randint(100000000, 999999999)) + file.filename
    file.save(path + filename)

    return {'code': 0, 'msg': 'succ', 'data': filename}


@socketio.on('connect', namespace='/adderss')
def connect_adderss():
    emit('test', {'code': 0, 'msg': 'succ'})


@socketio.on('putTxt', namespace='/adderss')
def handle_putTxt(data):
    data = str.splitlines(data['text'])

    emit('putTxt', {'code': 0, 'msg': 'succ', 'count': len(data)})
    gevent.joinall([gevent.spawn(words_start_text, data, request.sid)])


@socketio.on('upload', namespace='/adderss')
def handle_upload(data):
    print(path + data["data"])
    file = open(path + data["data"], encoding="utf8")

    text = file.read()
    file.close()
    data = str.splitlines(text)
    gevent.joinall([gevent.spawn(words_start_arr, data, request.sid)])


@socketio.on_error('/adderss')  # handles the '/chat' namespace
def error_handler_chat(e):
    print(e)


def words_start_arr(data, sid):
    i = 0

    count = len(data)
    if count > 500:
        a = math.ceil(count / 500)
        for item in range(a):
            i += 500
            data_temp = data[500 * item:1 * i]
            words = transform(data_temp)

            print(i / count)
            progress = math.ceil(i / count * 100)
            if i >= count:
                i = count
            gevent.sleep(0.01)
            socketio.emit('words_arr',
                          {'code': 0, 'msg': 'succ', 'data': words, 'countAll': count, 'count': i,
                           'progress': progress},
                          namespace='/adderss', room=sid)
    else:
        for item in data:
            i += 1
            words = transform([item])

            # 计算当前进度
            print(i / count)
            progress = math.ceil(i / count * 100)
            gevent.sleep(0.01)
            socketio.emit('words_arr',
                          {'code': 0, 'msg': 'succ', 'data': words, 'countAll': count, 'count': i,
                           'progress': progress},
                          namespace='/adderss', room=sid)


def words_start_text(data, sid):
    a = 0
    count = len(data)
    for item in data:
        a += 1
        words = transform([item])

        # 计算当前进度
        print(a / count)
        progress = math.ceil(a / count * 100)
        gevent.sleep(0.01)
        socketio.emit('words',
                      {'code': 0, 'msg': 'succ', 'data': words, 'countAll': count, 'count': a, 'progress': progress},
                      namespace='/adderss', room=sid)


def task_start_flask():
    'start the rest and ws server'
    socketio.run(app, ping_timeout=10, ping_interval=5)


if __name__ == '__main__':
    gevent.joinall([
        gevent.spawn(task_start_flask)
    ])
